package com.sgl.retrofitdemo.utils;

import com.orhanobut.logger.Logger;

import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.text.Collator;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by sunqiyong on 2016/11/13.
 */

public class SafetyUtil {
    private static String KEY = "Yoho9646";

    public SafetyUtil() {
    }

    public static String encryptStringToMd5(String src, String flag) {
        if(src != null && src.length() != 0) {
            MessageDigest md = null;
            Object b = null;
            boolean i = false;
            StringBuffer buf = null;

            try {
                md = MessageDigest.getInstance("MD5");
                md.update(src.getBytes());
                byte[] var8 = md.digest();
                buf = new StringBuffer("");

                for(int e = 0; e < var8.length; ++e) {
                    int var9 = var8[e];
                    if(var9 < 0) {
                        var9 += 256;
                    }

                    if(var9 < 16) {
                        buf.append("0");
                    }

                    buf.append(Integer.toHexString(var9));
                }

                if(flag != null) {
                    if(!flag.equals("16")) {
                        return buf.toString();
                    } else {
                        return buf.toString().substring(8, 24);
                    }
                } else {
                    return buf.toString();
                }
            } catch (NoSuchAlgorithmException var7) {
                var7.printStackTrace();
                return "";
            }
        } else {
            return null;
        }
    }

    public static String encryptBytesToMd5(byte[] bytes, String flag) {
        MessageDigest md = null;
        Object b = null;
        boolean i = false;
        StringBuffer buf = null;

        try {
            md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            byte[] var8 = md.digest();
            buf = new StringBuffer("");

            for(int e = 0; e < var8.length; ++e) {
                int var9 = var8[e];
                if(var9 < 0) {
                    var9 += 256;
                }

                if(var9 < 16) {
                    buf.append("0");
                }

                buf.append(Integer.toHexString(var9));
            }

            if(flag != null) {
                if(!flag.equals("16")) {
                    return buf.toString();
                } else {
                    return buf.toString().substring(8, 24);
                }
            } else {
                return buf.toString();
            }
        } catch (NoSuchAlgorithmException var7) {
            var7.printStackTrace();
            return "";
        }
    }

    private static Key initKeyForAES(String key) throws NoSuchAlgorithmException {
        if(key == null || key.length() == 0) {
            key = KEY;
        }

        SecretKeySpec key2 = null;

        try {
            KeyGenerator ex = KeyGenerator.getInstance("AES");

            try {
                SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
                sr.setSeed(key.getBytes());
                ex.init(128, sr);
            } catch (NoSuchProviderException var6) {
                var6.printStackTrace();
            }

            SecretKey secretKey = ex.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            key2 = new SecretKeySpec(enCodeFormat, "AES");
            return key2;
        } catch (NoSuchAlgorithmException var7) {
            throw new NoSuchAlgorithmException();
        }
    }

    public static String encryptAES(String content, String key) {
        if(key == null || key.length() == 0) {
            key = KEY;
        }

        try {
            SecretKeySpec e = (SecretKeySpec)initKeyForAES(key);
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(1, e);
            byte[] result = cipher.doFinal(byteContent);
            Logger.i("edsd", "AES加密:" + asHex(result));
            return asHex(result);
        } catch (Exception var6) {
            var6.printStackTrace();
            return null;
        }
    }

    public static String decryptAES(String content, String key) {
        if(key == null || key.length() == 0) {
            key = KEY;
        }

        try {
            SecretKeySpec e = (SecretKeySpec)initKeyForAES(key);
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(2, e);
            byte[] result = cipher.doFinal(asBytes(content));
            String password = new String(result);
            Logger.i("edsd", "AES解密:" + password);
            return password;
        } catch (Exception var6) {
            var6.printStackTrace();
            return null;
        }
    }

    private static String asHex(byte[] buf) {
        StringBuffer strbuf = new StringBuffer(buf.length * 2);

        for(int i = 0; i < buf.length; ++i) {
            if((buf[i] & 255) < 16) {
                strbuf.append("0");
            }

            strbuf.append(Long.toString((long)(buf[i] & 255), 16));
        }

        return strbuf.toString();
    }

    private static byte[] asBytes(String hexStr) {
        if(hexStr.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hexStr.length() / 2];

            for(int i = 0; i < hexStr.length() / 2; ++i) {
                int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
                result[i] = (byte)(high * 16 + low);
            }

            return result;
        }
    }

    public static String getRequestSecretString(String privateKey, String parameters) {
        String strSecret = null;
        if(parameters != null && parameters.length() != 0) {
            if(parameters.indexOf("private_key=") < 0) {
                parameters = parameters + "private_key=" + privateKey;
            }

            parameters = parameters.replaceAll(" ", "");
            parameters = parameters.replaceAll("\n", "");
            parameters = parameters.replaceAll("\r", "");
            parameters = parameters.replaceAll("\t", "");
            String[] arr = parameters.split("&");
            Collator cmp = Collator.getInstance(Locale.ENGLISH);
            Arrays.sort(arr, cmp);
            String sortParameters = "";

            for(int i = 0; i < arr.length; ++i) {
                if(i == 0) {
                    sortParameters = arr[i];
                } else {
                    sortParameters = sortParameters + "&" + arr[i];
                }
            }

            Logger.d("sss", "sortParameters: " + sortParameters);
            strSecret = encryptStringToMd5(sortParameters, "32");
            return strSecret;
        } else {
            return null;
        }
    }

    public static String getRequestSecretString(String privateKey, Map<String, String> parametersMap) {
        String strParameters = "private_key=" + privateKey;
        if(parametersMap != null && parametersMap.size() > 0) {
            Iterator var4 = parametersMap.entrySet().iterator();

            while(var4.hasNext()) {
                Map.Entry entry = (Map.Entry)var4.next();
                if(entry != null) {
                    String key = (String)entry.getKey();
                    String value = (String)entry.getValue();
                    if(key != null && key.length() != 0 && value != null && value.length() != 0) {
                        strParameters = strParameters + "&" + key + "=" + value;
                    }
                }
            }
        }

        return getRequestSecretString(privateKey, strParameters);
    }
}
